package com.jajb.controldeiluminacion;

import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;

import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {
    //Identificadores para Arduino
    static final String ARDUINO_CONFIG = "C";
    static final String ARDUINO_SWITCH_1 = "S1@";
    static final String ARDUINO_SWITCH_2 = "S2@";
    static final String ARDUINO_SWITCH_3 = "S3@";
    static final String ARDUINO_SWITCH_4 = "S4@";

    static final int RECEIVE_MESSAGE = 1;

    private BluetoothHelper btHelper;
    private Handler handler;
    private StringBuilder sb = new StringBuilder();

    SerialDataHelper sdHelper;

//----------------------------------------------------------------------------------------------------------
// CREACION
//----------------------------------------------------------------------------------------------------------

    //------------------------------------------------------------------------------------
    // En onCreate se registra el Helper del bluetooth, se crea un broadcast receiver para
    // el cambio de estado del bluetooth y se manejan los mensajes entrantes del host

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Pantalla siempre encendida
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        //Click del boton de configuracion de PIN
        Button btnConfiguracion = (Button) findViewById(R.id.btnConfiguracion);
        btnConfiguracion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showCustomDialog();
            }
        });

        handler = new Handler() {
            public void handleMessage(android.os.Message msg) {

                if (msg.what == btHelper.RECEIVE_MESSAGE_BLUETOOTH) //Obtiene datos del arduino
                {
                    SerialDataHelper.ReadData(msg);
                    String strTemperatura = SerialDataHelper.GetValue('T');
                    String strHumedad = SerialDataHelper.GetValue('H');

                    if (!strTemperatura.equals("")) {
                        final TextView tvTemp = (TextView) findViewById(R.id.tvTemp);
                        tvTemp.setText(strTemperatura + " ºC");
                    }

                    if (!strHumedad.equals("")) {
                        final TextView tvHum = (TextView) findViewById(R.id.tvHum);
                        tvHum.setText(strHumedad + " %");
                    }
                }
            }

            ;
        };

        // Crea instancia para la clase helper de bluetooth
        btHelper = new BluetoothHelper(handler);

        //Registra Receiver de cambio de estado del Bluetooth
        registerReceiver(bluetoothReceiver, new IntentFilter("android.bluetooth.adapter.action.STATE_CHANGED"));

        if (!btHelper.EsHabilitado()) {
            appMsg(getApplicationContext().getString(R.string.HabilitarBT));
            finish();
            return;
        }
    }


//----------------------------------------------------------------------------------------------------------
// EVENTOS FRONT
//----------------------------------------------------------------------------------------------------------

    //------------------------------------------------------------------------------------
    // Ejecuta el click en los botones para enviar los mensajes a Arduino

    public void clickBtnSwitch1(View view) {
        btHelper.btConnectedThread.write(ARDUINO_SWITCH_1);
    }

    public void clickBtnSwitch2(View view) {
        btHelper.btConnectedThread.write(ARDUINO_SWITCH_2);
    }

    public void clickBtnSwitch3(View view) {
        btHelper.btConnectedThread.write(ARDUINO_SWITCH_3);
    }

    public void clickBtnSwitch4(View view) {
        btHelper.btConnectedThread.write(ARDUINO_SWITCH_4);
    }


    //------------------------------------------------------------------------------------
    // Muestra una ventana para establecer el PIN del dispositivo bluetooth

    protected void showCustomDialog() {
        final Dialog dialog = new Dialog(MainActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.configuration);

        final EditText etPIN = (EditText) dialog.findViewById(R.id.etPIN);

        Button btnAceptar = (Button) dialog.findViewById(R.id.btnAceptar);
        btnAceptar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etPIN.getText().toString().length() == 4) {
                    btHelper.btConnectedThread.write(ARDUINO_CONFIG + etPIN.getText().toString() + "@");
                    dialog.dismiss();
                } else {
                    appMsg(getApplicationContext().getString(R.string.LongitudPIN));
                }
            }
        });

        Button btnCancelar = (Button) dialog.findViewById(R.id.btnCancelar);
        btnCancelar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
    }


//----------------------------------------------------------------------------------------------------------
// METODOS OVERRIDE
//----------------------------------------------------------------------------------------------------------

    //------------------------------------------------------------------------------------
    // Al entrar a onResume se conecta al dispositivo e inicia thread para obtener datos

    @Override
    public void onResume() {
        super.onResume();

        if (btHelper.Conecta()) {
            appMsg(getApplicationContext().getString(R.string.ConexionRealizada));
        } else {
            appMsg(getApplicationContext().getString(R.string.NoConexionRealizada));
            finish();
            return;
        }
    }


    //------------------------------------------------------------------------------------
    // Al entrar a onPause se desconecta del dispositivo

    @Override
    public void onPause() {
        super.onPause();

        btHelper.Desconecta();
    }


    //------------------------------------------------------------------------------------
    // Al presionar la tecla Back, se desconecta del dispositivo y cierra el programa

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            btHelper.Desconecta();
            appMsg(getApplicationContext().getString(R.string.CerrandoApp));
            finish();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


//----------------------------------------------------------------------------------------------------------
// METODOS
//----------------------------------------------------------------------------------------------------------

    //------------------------------------------------------------------------------------
    // Manda un aviso

    private void appMsg(String message) {
        Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
    }


//----------------------------------------------------------------------------------------------------------
// BROADCAST RECEIVERS
//----------------------------------------------------------------------------------------------------------

    //------------------------------------------------------------------------------------
    // Crea un BroadcastReceiver para obtener cambios del estado del bluetooth

    private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                if ((btHelper.ObtieneEstado() == BluetoothAdapter.STATE_OFF || btHelper.ObtieneEstado() == BluetoothAdapter.STATE_TURNING_OFF)) {
                    appMsg(getApplicationContext().getString(R.string.HabilitarBT));
                    finish();
                    return;
                }
            }
        }
    };
}









